#! /bin/bash

port=$1
debug_port=$2
env=$3
project_name=$4
project_path_name=$5
project_jar_name=$6
isBuild=${7:-true}

##总说明
##编译该项目并发布到指定目录下

d=`date "+%Y-%m-%d %H:%M:%S"`
st=`date -d "${d}" +%s`
echo "--------------------当前日期:${d}--------------------"

echo "--------------------拉取项目--------------------"
project_path=/home/devops/workspace/${project_path_name}
cd ${project_path}
git pull origin master
echo "--------------------拉取项目完成...--------------------"

jar_name="${project_jar_name}"
echo "--------------------jar名称:${jar_name}"

jar_target="/home/devops/workspace/${project_path_name}/${project_name}"
echo "--------------------jar目录:${jar_target}"

jar_product="/home/devops/deploy/${project_path_name}/"
# 检查目录是否存在
if [ ! -d "$jar_product" ]; then
    # 如果目录不存在，则创建目录
    mkdir -p "$jar_product"
    echo "--------------------目录 $jar_product 创建成功--------------------"
else
    # 如果目录已经存在，则不进行任何操作
    echo "--------------------目录 $jar_product 已经存在，无需创建--------------------"
fi
echo "--------------------生产目录:${jar_product}"

#mvnd_exec="/home/devops/soft/maven-mvnd-1.0-m8-m40-linux-amd64/bin/"
#echo "--------------------mvn执行路径:${mvnd_exec}"

if( $isBuild = true); then
  echo "--------------------开始构建项目${jar_target}--------------------"
  cd ${jar_target}
  mvnd clean
  sleep 5
  mvnd install
  sleep 5
  mvnd package -U -Dmaven.test.skip=true
  echo "--------------------完成构建项目--------------------"
fi


echo "--------------------端口:${port}--------------------"
java_ps_id=$(netstat -nlp | grep :${port} | awk '{print $7}' | awk -F"/" '{ print $1 }')

echo "--------------------Java进程id:${java_ps_id}--------------------"
if((java_ps_id>0)); then
 echo "-------------------->>杀死java进程:${java_ps_id}"
 kill -15 ${java_ps_id}
 sleep 5
fi

#清空发布目录的文件
echo "--------------------开始清除发布目录文件--------------------"
cd ${jar_product}
for file in ${jar_product}/*; do
  fileName=${file##*/}
  if [[ ${fileName} == *log* ]]; then
       echo "-------------------->跳过:${jar_product}${fileName}"
     else
       echo "-------------------->删除:${jar_product}${fileName}"
       rm -rf "${jar_product}${fileName}"
  fi
done
echo "--------------------清除发布目录文件完成--------------------"

echo "--------------------复制文件--------------------"
#复制编译好的文件到发布目录
cp -rf "${jar_target}/target/${jar_name}.jar" ${jar_product}

d=`date "+%Y-%m-%d %H:%M:%S"`
##计算耗时
ed=`date -d "${d}" +%s`
tt=$[ed-st]
fen=0
second=${tt}
if((tt>60));then
  fen=$[tt/60]
  second=$((tt%60))
fi

echo "--------------------启动java程序--------------------"

cd ${jar_product}
nohup java -agentlib:jdwp=transport=dt_socket,address=*:${debug_port},server=y,suspend=n -jar ${jar_name}.jar --solon.env=${env} > ${jar_name}.log 2>&1 &
tail -111f ~/deploy/${jar_name}/${jar_name}.log
echo "--------------------完成:${d}--------------------"
echo "--------------------耗时:${fen}分${second}秒--------------------"